package com.atguigu.xuexiplus.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import java.security.Principal;
import java.util.Map;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*")
                .setHandshakeHandler(new UserHandshakeHandler())
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic", "/queue");
        registry.setApplicationDestinationPrefixes("/app");
        registry.setUserDestinationPrefix("/user");
    }

    /**
     * 自定义握手，将连接参数中的 userId 作为用户标识，用于 /user/queue/messages 路由
     */
    static class UserHandshakeHandler extends DefaultHandshakeHandler {
        @Override
        protected Principal determineUser(org.springframework.http.server.ServerHttpRequest request,
                                          org.springframework.web.socket.WebSocketHandler wsHandler,
                                          Map<String, Object> attributes) {
            // 从 URL 查询参数中取 userId
            String userId = null;
            if (request instanceof org.springframework.http.server.ServletServerHttpRequest servletReq) {
                var httpReq = servletReq.getServletRequest();
                userId = httpReq.getParameter("userId");
                if (userId == null || userId.isBlank()) {
                    // 兼容使用 username 作为标识
                    userId = httpReq.getParameter("username");
                }
            }
            final String name = (userId == null || userId.isBlank()) ? ("anon-" + java.util.UUID.randomUUID()) : userId;
            return () -> name;
        }
    }
}


